/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dieci.database.product;

import dieci.database.PersistentObject;
import dieci.database.SessionFactoryUtil;
import dieci.hibernate.HibProduct;
import dieci.hibernate.HibProductStock;
import dieci.managers.stockmanager.ProductManager;
import dieci.system.Product;
import dieci.system.ProductStock;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Blanco
 */
public class ProductStockHibernateDAO implements ProductStockDAO {
    
    private static Logger logger = Logger.getLogger("ProductStockDAO.log");

    private ProductManager productManager = new ProductManager();
    
    @Override
    public List<ProductStock> list()
    {
        List<ProductStock> products = new ArrayList<>();

        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibProductStock> hibProductStocks = session.createCriteria(HibProductStock.class).list();
            for (HibProductStock dbProd : hibProductStocks) {
                Product prod = findProductById(dbProd.getProductId());
                ProductStock prodStock = new ProductStock(prod, dbProd.getAvailableAmount(), 
                        dbProd.getOnReturnAmount(), dbProd.getTotalAmount());
                products.add(prodStock);
            }

            return products;
        }
        catch (Exception e) {

            logger.log(Level.INFO, "Error listando productos", e.getMessage());

            throw new IllegalStateException("Error al listar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public void saveOrUpdate(PersistentObject object)
    {
        Session session = null;

        ProductStock prod = (ProductStock) object;
        ProductStock found = findByProductId(prod.getProduct().getProductId());
        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();
            
            session.beginTransaction();

            HibProductStock hibProductStock;
            if (found != null) 
            {
                //UPDATE
                prod.getProduct().setProductId(found.getProduct().getProductId());
            }
            
            hibProductStock = new HibProductStock(prod);
            session.saveOrUpdate(hibProductStock);
            session.getTransaction().commit();

        }
        catch (Exception e) {
            if(session!=null){
                session.getTransaction().rollback();
            }            
            throw new IllegalStateException("Error al guardar o actualizar",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public ProductStock findByProductId(long id)
    {
        ProductStock result = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            HibProductStock hibProductStock = (HibProductStock) session.createCriteria(HibProductStock.class).add(Restrictions.eq("productId", id)).uniqueResult();
            if (hibProductStock != null) {
                Product prod = findProductById(id);
                result = new ProductStock(prod, hibProductStock.getAvailableAmount(), hibProductStock.getOnReturnAmount(),
                        hibProductStock.getTotalAmount());
            }

        }
        catch (Exception e) {
            throw new IllegalStateException("Error al buscar por id",e);
        }
        finally {
            if (session!=null && session.isOpen()) {

                session.close();
            }
        }

        return result;
    
    }

    @Override
    public void delete(PersistentObject object)
    {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private Product findProductById(long id){
        return productManager.findById(id);
    }
    
}
